package com.dp.appi.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dp.appi.dao.PhotoDao;

import com.dp.appi.service.PhotoService;
import com.dp.appi.util.FileUtil;
import com.dp.appi.util.ImageUtils;
import com.dp.appi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.*;

/**
 * Created by chenghao on 2015/9/30.
 */
@Service
public class PhotoServiceImpl implements PhotoService {
    @Autowired
    private PhotoDao photoDao;

    @Value("${file_path}")
    private String file_path;
    @Override
    public List<Map<String, Object>> getPhotoTypeByOrgId(String orgid) {
        return photoDao.getPhotoTypeByOrgId(orgid);
    }
    @Override
    public  List<Map<String,Object>> getRecordProject(Long stageid, Long lasttime){
        return photoDao.getRecordProject(stageid,lasttime);
    }
    @Override
    public  List<Map<String,Object>> getPhoneProject(Long stageid,Long lasttime){
        return photoDao.getPhoneProject(stageid,lasttime);
    }
    @Override
    public Long analysisPackage(String path,String stageId) {
        String stageReName = "ProjectStagePhInfo_*.tio";

        //照片

        JSONArray arr = parseFileToJSONArray(path, stageReName);
        if (arr != null && arr.size() > 0) {
            for (int i = 0; i < arr.size(); i++) {
                JSONObject objtemp = arr.getJSONObject(i);
                JSONArray array1 = objtemp.getJSONArray("recordList");
                for (int h = 0; h < array1.size(); h++) {
                    JSONObject reObj = array1.getJSONObject(h);
                    if( reObj.get("isdel").toString().equals("删除"))
                    {
                        String dlsql="update z_record set isdel='删除' , lasttime=:lasttime where guid=:guid";
                        Map prd= new HashMap<>();
                        prd.put("guid",reObj.get("guid") );
                        prd.put("lasttime", new Date().getTime() );
                        photoDao.executeSql(dlsql,prd);
                    }
                    if( reObj.get("isdel").toString().equals("新增"))
                    {
                        String dlsql=" INSERT INTO z_record (guid,sid,pid,pname,plist,founderid,foundertime,pileseat,kwords,remarks,isdel,lasttime) VALUES (:guid,:sid,:pid,:pname,:plist,:founderid,:foundertime,:pileseat,:kwords,:remarks,:isdel,:lasttime)";
                        Map prd= new HashMap<>();
                        prd.put("guid",reObj.get("guid") );
                        prd.put("sid",reObj.get("sid") );
                        prd.put("pid",reObj.get("pid") );
                        prd.put("pname",reObj.get("pname") );
                        prd.put("plist",reObj.get("plist") );
                        prd.put("founderid",reObj.get("founderid") );
                        prd.put("foundertime", reObj.get("foundertime") );
                        prd.put("pileseat",reObj.get("pileseat") );
                        prd.put("kwords",reObj.get("kwords") );
                        prd.put("remarks",reObj.get("remarks") );
                        prd.put("isdel","新增" );
                        prd.put("lasttime", new Date().getTime() );
                        photoDao.executeSql(dlsql,prd);
                    }
                    if( reObj.get("isdel").toString().equals("修改"))
                    {
                        String dlsql="update z_record set pid=:pid,pname= :pname , plist=:plist,pileseat=:pileseat,kwords=:kwords,  isdel='修改' , lasttime=:lasttime where guid=:guid";
                        Map prd= new HashMap<>();
                        prd.put("guid",reObj.getString("guid") );
                        prd.put("pid",reObj.getLongValue("pid") );
                        prd.put("pname",reObj.getString("pname") );
                        prd.put("plist",reObj.getString("plist") );
                        prd.put("pileseat",reObj.getString("pileseat") );
                        prd.put("kwords",reObj.getString("kwords") );
                        prd.put("lasttime", new Date().getTime() );
                        photoDao.executeSql(dlsql,prd);
                    }
                }




                JSONArray array2 = objtemp.getJSONArray("photoList");
                for (int h = 0; h < array2.size(); h++) {
                    JSONObject phObj = array2.getJSONObject(h);
                    if( phObj.getString("isdel").equals("删除"))
                    {
                        String dlsql="update z_photo set isdel='删除' , lasttime=:lasttime where guid=:guid";
                        Map prd= new HashMap<>();
                        prd.put("guid",phObj.get("guid") );
                        prd.put("lasttime", new Date().getTime() );
                        photoDao.executeSql(dlsql,prd);
                    }
                    if( phObj.getString("isdel").equals("新增"))
                    {

                      String imgurl=  copPhoto(phObj,  path);
                        String dlsql=" INSERT INTO z_photo (guid,sid,rguid,plistone,remarks,longitude,latitude,founderid,foundertime,imgname,imgaddress,imgurl,isdel,lasttime) VALUES (:guid,:sid,:rguid,:plistone,:remarks,:longitude,:latitude,:founderid,:foundertime,:imgname,:imgaddress,:imgurl,:isdel,:lasttime)";
                        Map prd= new HashMap<>();
                        prd.put("guid",phObj.getString("guid") );
                        prd.put("sid",phObj.getLong("sid") );
                        prd.put("rguid",phObj.getString("rguid") );
                        prd.put("plistone",phObj.getString("plistone") );
                        prd.put("remarks",phObj.getString("remarks") );
                        prd.put("longitude",phObj.getDouble("longitude") );
                        prd.put("latitude",phObj.getDouble("latitude") );
                        prd.put("founderid",phObj.getString("founderid") );
                        prd.put("foundertime",phObj.getLong("foundertime") );
                        prd.put("imgname",phObj.getString("imgname") );
                        prd.put("imgaddress",phObj.getString("imgaddress") );
                        prd.put("imgurl",imgurl );
                        prd.put("isdel","新增" );
                        prd.put("lasttime", new Date().getTime() );
                        photoDao.executeSql(dlsql,prd);
                    }
                }


            }
        }

         return Long.parseLong("0");
    }


    @Override
    public Long analysisPackageproblem(String path,String stageId) {
        String stageReName = "ProjectStageProblemInfo_*.tio";

        //照片

        JSONArray arr = parseFileToJSONArray(path, stageReName);
        if (arr != null && arr.size() > 0) {
            for (int i = 0; i < arr.size(); i++) {
                JSONObject objtemp = arr.getJSONObject(i);
                JSONArray array1 = objtemp.getJSONArray("problemExistList");
                for (int h = 0; h < array1.size(); h++) {
                    JSONObject reObj = array1.getJSONObject(h);
                    if( reObj.get("states").toString().equals("删除"))
                    {
                        String dlsql="update p_problemExist set states='删除'  where guid=:guid";
                        Map prd= new HashMap<>();
                        prd.put("guid",reObj.get("guid") );
                        photoDao.executeSql(dlsql,prd);
                    }
                    if( reObj.get("states").toString().equals("新增"))
                    {
                        String dlsql=" INSERT INTO p_problemExist (guid,bigType,smallType,existDescribe,advice," +
                                "problemGuid,finder,findTime,note,handler,handleTime,results," +
                                "accepter,acceptTime,pointId,projectId,states) VALUES " +
                                "(:guid,:bigType,:smallType,:existDescribe,:advice," +
                                ":problemGuid,:finder,:findTime,:note,:handler,:handleTime,:results," +
                                ":accepter,:acceptTime,:pointId,:projectId,:states)";


                        Map prd= new HashMap<>();
                        prd.put("guid",reObj.get("guid") );
                        prd.put("bigType",reObj.get("bigType") );
                        prd.put("smallType",reObj.get("smallType") );
                        prd.put("existDescribe",reObj.get("existDescribe") );
                        prd.put("advice",reObj.get("advice") );
                        prd.put("problemGuid",reObj.get("problemGuid") );
                        prd.put("finder", reObj.get("finder") );
                        Long  findTimelong = Long.parseLong(reObj.get("findTime").toString());
                        Date findTime =new Date(findTimelong);
                        prd.put("findTime",findTime );
                        prd.put("note",reObj.get("note") );
                        prd.put("handler",reObj.get("handler") );
                        Long  handleTimelong = Long.parseLong(reObj.get("handleTime").toString());
                        Date handleTime =new Date(handleTimelong);
                        prd.put("handleTime",handleTime );
                        prd.put("results",reObj.get("results") );
                        prd.put("accepter",reObj.get("accepter") );

                        Long  acceptTimelong = Long.parseLong(reObj.get("acceptTime").toString());
                        Date acceptTime =new Date(acceptTimelong);
                        prd.put("acceptTime",acceptTime);
                        prd.put("pointId",reObj.get("pointId") );
                        prd.put("projectId",reObj.get("projectId") );
                        prd.put("states","新增" );

                        photoDao.executeSql(dlsql,prd);
                    }
                    if( reObj.get("states").toString().equals("修改"))
                    {
                        String dlsql="update z_record set " +
                                "bigType=:bigType,smallType= :smallType , existDescribe=:existDescribe," +
                                "advice=:advice,problemGuid=:problemGuid, finder=:finder," +
                                "findTime=:findTime,note=:note, handler=:handler,handleTime=:handleTime," +
                                "results=:results,acceptTime=:acceptTime, pointId=:pointId,projectId=:projectId," +
                                " states='修改'  where guid=:guid";
                        Map prd= new HashMap<>();
                        prd.put("guid",reObj.get("guid") );
                        prd.put("bigType",reObj.get("bigType") );
                        prd.put("smallType",reObj.get("smallType") );
                        prd.put("existDescribe",reObj.get("existDescribe") );
                        prd.put("advice",reObj.get("advice") );
                        prd.put("problemGuid",reObj.get("problemGuid") );
                        prd.put("finder", reObj.get("finder") );
                        Long  findTimelong = Long.parseLong(reObj.get("findTime").toString());
                        Date findTime =new Date(findTimelong);
                        prd.put("findTime",findTime );
                        prd.put("note",reObj.get("note") );
                        prd.put("handler",reObj.get("handler") );
                        Long  handleTimelong = Long.parseLong(reObj.get("handleTime").toString());
                        Date handleTime =new Date(handleTimelong);
                        prd.put("handleTime",handleTime );
                        prd.put("results",reObj.get("results") );
                        prd.put("accepter",reObj.get("accepter") );
                        Long  acceptTimelong = Long.parseLong(reObj.get("acceptTime").toString());
                        Date acceptTime =new Date(acceptTimelong);
                        prd.put("acceptTime",acceptTime);
                        prd.put("pointId",reObj.get("pointId") );
                        prd.put("projectId",reObj.get("projectId") );

                        photoDao.executeSql(dlsql,prd);
                    }
                }




                JSONArray array2 = objtemp.getJSONArray("problemExistPhotoList");
                for (int h = 0; h < array2.size(); h++) {
                    JSONObject phObj = array2.getJSONObject(h);
                    if( phObj.getString("states").equals("删除"))
                    {
                        String dlsql="update p_problemExistPhoto set states='删除'  where guid=:guid";
                        Map prd= new HashMap<>();
                        prd.put("guid",phObj.get("guid") );
                        photoDao.executeSql(dlsql,prd);
                    }
                    if( phObj.getString("states").equals("新增"))
                    {

                        String imgurl=  copyPhoto(phObj,  path,stageId);
                        String dlsql=" INSERT INTO p_problemExistPhoto " +
                                "(guid,problemExistGuid,photoName,phoneUrls,computerUrls,states)" +
                               " VALUES (:guid,:problemExistGuid,:photoName,:phoneUrls,:computerUrls,:states)";
                        Map prd= new HashMap<>();
                        prd.put("guid",phObj.getString("guid") );
                        prd.put("problemExistGuid",phObj.getString("problemExistGuid") );
                        prd.put("photoName",phObj.getString("photoName") );
                        prd.put("computerUrls",imgurl );
                        prd.put("phoneUrls",phObj.getString("phoneUrls")  );

                        prd.put("states","新增" );

                        photoDao.executeSql(dlsql,prd);
                    }
                }


            }
        }

        return Long.parseLong("0");
    }



    /**
     * 解析文件到JSONArray
     *
     * @param baseDIR  压缩包根目录路径
     * @param fileName 查找文件
     */
    public JSONArray parseFileToJSONArray(String baseDIR, String fileName) {
        List resultList = new ArrayList();
        FileUtil.findFiles(baseDIR, fileName, resultList);
        if (resultList.size() == 0) {
//            throw new PackageRuntimeException(SYS.PACK0001.name());
            return null;
        } else {//项目阶段文件只有一个
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < resultList.size(); i++) {
                JSONObject obj = JSONObject.parseObject(FileUtil.readFile((File) resultList.get(i)));
                jsonArray.add(obj);
            }
            return jsonArray;
        }
    }



    /**
     *  处理随手拍照片
     *
     * @param obj
     * @param path 文件目录
     */
    public String copPhoto(JSONObject obj, String path) {
        //先转移图片到upload目路
        String imgurl = "";
        String photo_url = obj.getString("imgname");
        if (StringUtil.isNotEmpty(photo_url)) {
            List resultList = new ArrayList();
            FileUtil.findFiles(path, photo_url, resultList);

            if (resultList.size() > 0) {
                File file = (File) resultList.get(0);
                String photo_sid = obj.getString("sid");
                String tempPath = "stage_" + photo_sid + "/";

                String[] _files = photo_url.split("\\.");
                String suffix = _files[1];
                String filename = _files[0];
                File fileDir = new File(file_path + tempPath);
                if (!fileDir.exists()) {
                    fileDir.mkdirs();
                }
                FileUtil.fileRomoveTo(file, file_path + tempPath + photo_url);
                imgurl = "upload/" + tempPath + photo_url;
            }

        }
        return imgurl;
    }

    /**
     *  隐患照片处理
     *
     * @param obj
     * @param path 文件目录
     */
    public String copyPhoto(JSONObject obj, String path,String stageId) {
        //先转移图片到upload目路
        String imgurl = "";
        String photo_url = obj.getString("photoName");
        if (StringUtil.isNotEmpty(photo_url)) {
            List resultList = new ArrayList();
            FileUtil.findFiles(path, photo_url, resultList);

            if (resultList.size() > 0) {
                File file = (File) resultList.get(0);

                String tempPath = "problem_" + stageId + "/";

                String[] _files = photo_url.split("\\.");
                String suffix = _files[1];
                String filename = _files[0];
                File fileDir = new File(file_path + tempPath);
                if (!fileDir.exists()) {
                    fileDir.mkdirs();
                }
                FileUtil.fileRomoveTo(file, file_path + tempPath + photo_url);
                imgurl = "upload/" + tempPath + photo_url;
            }

        }
        return imgurl;
    }


}
